package com.qianfeng.day1029.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * author: 田晋宇
 * datetime:2021/10/29 9:34
 * email:853796359@qq.com
 */

@RestController
public class OrderController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/init")
    public String init(){

        stringRedisTemplate.opsForValue().set("stock","100");
        return "ok";
    }
    @Autowired
    private Redisson redisson;

    @Autowired
    private CuratorFramework cf;

    @RequestMapping("/order")
    public String createOrder() throws Exception {

        String key="bangbang";
        String value = UUID.randomUUID().toString();

        InterProcessMutex mutex = new InterProcessMutex(cf, "/order");
        mutex.acquire();//加锁
        //RLock lock = redisson.getLock(key);


        //lock.lock(10, TimeUnit.SECONDS);

        int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));


        if(stock<=0){
            //lock.unlock();//释放锁
            mutex.release();
            return "商品售罄 请参与下次活动!!!";
        }

        stringRedisTemplate.opsForValue().set("stock",stock-1+"");
        System.out.println("抢购成功  目前库存" + (stock - 1));
        //lock.unlock();
        mutex.release();
        return  "抢购成功  目前库存"+(stock-1);


    }
}
